using Consul;
using Microsoft.AspNetCore.Mvc;

namespace ServiceCenter.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ConsulController : ControllerBase
    {
        private readonly IConsulClient _consulClient;
        public ConsulController(IConsulClient consulClient)
        {
            _consulClient = consulClient;
        }

        // 注册服务
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] AgentServiceRegistration registration)
        {
            await _consulClient.Agent.ServiceRegister(registration);
            return Ok("Service registered.");
        }

        // 注销服务
        [HttpPost("deregister")]
        public async Task<IActionResult> Deregister([FromQuery] string serviceId)
        {
            await _consulClient.Agent.ServiceDeregister(serviceId);
            return Ok("Service deregistered.");
        }

        // 获取所有服务
        [HttpGet("services")]
        public async Task<IActionResult> GetServices()
        {
            var services = await _consulClient.Agent.Services();
            return Ok(services.Response.Values);
        }

        // 获取健康服务
        [HttpGet("health/services")]
        public async Task<IActionResult> GetHealthyServices([FromQuery] string serviceName)
        {
            var health = await _consulClient.Health.Service(serviceName, tag: null, passingOnly: true);
            return Ok(health.Response.Select(x => new {
                x.Service.ID,
                x.Service.Service,
                x.Service.Address,
                x.Service.Port,
                x.Checks
            }));
        }
    }
} 